# -*- coding: utf-8 -*-
"""
Hive元数据监控系统 - Python长期方案
主服务入口
"""

import os
import sys
import yaml
import logging
import argparse
import signal
from logging.handlers import RotatingFileHandler

# 添加common目录到路径
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from storage import DatabaseManager
from core import MonitorEngine
from api.app import create_app


# 配置日志
def setup_logging(log_level='INFO', log_file=None):
    """配置日志系统"""
    logger = logging.getLogger()
    logger.setLevel(getattr(logging, log_level.upper()))
    
    # 日志格式
    formatter = logging.Formatter(
        '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
    )
    
    # 控制台处理器
    console_handler = logging.StreamHandler()
    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    
    # 文件处理器
    if log_file:
        os.makedirs(os.path.dirname(log_file), exist_ok=True)
        file_handler = RotatingFileHandler(
            log_file,
            maxBytes=100 * 1024 * 1024,  # 100MB
            backupCount=10
        )
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)


# 加载配置
def load_config(config_path='config.yaml'):
    """加载配置文件"""
    if not os.path.exists(config_path):
        # 尝试从示例配置创建
        example_path = 'config.example.yaml'
        if os.path.exists(example_path):
            import shutil
            shutil.copy(example_path, config_path)
            print(f"已从示例配置创建配置文件: {config_path}")
        else:
            raise FileNotFoundError(f"配置文件不存在: {config_path}")
    
    with open(config_path, 'r', encoding='utf-8') as f:
        config = yaml.safe_load(f)
    
    return config


# 主类
class MonitorService:
    """监控服务"""
    
    def __init__(self, config_path='config.yaml'):
        # 加载配置
        self.config = load_config(config_path)
        
        # 设置日志
        log_config = self.config.get('logging', {})
        setup_logging(
            log_level=log_config.get('level', 'INFO'),
            log_file=log_config.get('file')
        )
        
        self.logger = logging.getLogger(__name__)
        self.logger.info("=" * 60)
        self.logger.info("Hive元数据监控系统 - Python长期方案")
        self.logger.info("=" * 60)
        
        # 初始化组件
        self.db_manager = None
        self.monitor_engine = None
        self.flask_app = None
        
        # 注册信号处理
        signal.signal(signal.SIGINT, self._signal_handler)
        signal.signal(signal.SIGTERM, self._signal_handler)
    
    def _signal_handler(self, signum, frame):
        """信号处理器"""
        self.logger.info(f"收到信号 {signum}，准备退出...")
        self.stop()
        sys.exit(0)
    
    def initialize(self):
        """初始化所有组件"""
        self.logger.info("正在初始化组件...")
        
        # 1. 初始化数据库
        db_path = self.config.get('database', {}).get('path', 'data/monitor.db')
        self.db_manager = DatabaseManager(db_path)
        self.logger.info("✓ 数据库初始化完成")
        
        # 2. 初始化监控引擎
        self.monitor_engine = MonitorEngine(self.config, self.db_manager)
        self.logger.info("✓ 监控引擎初始化完成")
        
        # 3. 创建Flask应用
        self.flask_app = create_app(self.config, self.db_manager, self.monitor_engine)
        self.logger.info("✓ API服务初始化完成")
        
        self.logger.info("所有组件初始化完成")
    
    def start(self):
        """启动服务"""
        self.logger.info("正在启动服务...")
        
        # 初始化组件
        self.initialize()
        
        # 启动监控引擎
        self.monitor_engine.start()
        self.logger.info("✓ 监控引擎已启动")
        
        # 启动API服务
        api_config = self.config.get('api', {})
        host = api_config.get('host', '0.0.0.0')
        port = api_config.get('port', 8080)
        debug = api_config.get('debug', False)
        
        self.logger.info(f"✓ API服务启动在 http://{host}:{port}")
        self.logger.info("=" * 60)
        self.logger.info("服务已启动！")
        self.logger.info(f"Web界面: http://localhost:{port}")
        self.logger.info(f"API文档: http://localhost:{port}/api/status")
        self.logger.info("=" * 60)
        
        # 运行Flask应用
        self.flask_app.run(
            host=host,
            port=port,
            debug=debug,
            use_reloader=False  # 避免双重启动
        )
    
    def stop(self):
        """停止服务"""
        self.logger.info("正在停止服务...")
        
        if self.monitor_engine:
            self.monitor_engine.stop()
            self.logger.info("✓ 监控引擎已停止")
        
        self.logger.info("服务已停止")


def main():
    """主函数"""
    parser = argparse.ArgumentParser(
        description='Hive元数据监控系统 - Python长期方案'
    )
    parser.add_argument(
        '-c', '--config',
        default='config.yaml',
        help='配置文件路径 (default: config.yaml)'
    )
    parser.add_argument(
        '--check',
        action='store_true',
        help='仅检查配置和环境'
    )
    
    args = parser.parse_args()
    
    if args.check:
        # 检查模式
        print("检查配置文件...")
        try:
            config = load_config(args.config)
            print("✓ 配置文件有效")
            
            # 检查必要的配置项
            required_keys = ['mysql', 'feishu', 'monitor']
            for key in required_keys:
                if key not in config:
                    print(f"✗ 缺少配置项: {key}")
                else:
                    print(f"✓ 配置项存在: {key}")
            
            print("\n配置检查完成")
        except Exception as e:
            print(f"✗ 配置检查失败: {e}")
            sys.exit(1)
    else:
        # 正常启动模式
        try:
            service = MonitorService(args.config)
            service.start()
        except KeyboardInterrupt:
            print("\n收到中断信号，退出...")
        except Exception as e:
            print(f"服务启动失败: {e}")
            import traceback
            traceback.print_exc()
            sys.exit(1)


if __name__ == '__main__':
    main()

